import router from '@/router';
import axios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios';
import { ElLoading, ElMessage } from 'element-plus';
import { RequestOptionsType, RequestResponse } from 'types/request';
import { ref } from 'vue';
import { getAppEnvConfig } from '../hooks/useEnv';
import storage from './storage';

const env = getAppEnvConfig()

const agent = {
	host: env.VITE_PROXY_HOST,
	port: env.VITE_PROXY_PORT,
}
let fullscreenLoading = ref()
let openFullScreen  = () => {
	fullscreenLoading.value = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
}

let closeFullScreen = () => {
	fullscreenLoading.value && fullscreenLoading.value.close()
}

const service: AxiosInstance = axios.create({
	baseURL: env.VITE_GLOB_API_URL,
	timeout: env.VITE_GLOB_AXIOS_TIMEOUT || 100000,
	proxy: env.VITE_PROXY_OPEN ? agent : undefined
});


service.interceptors.request.use(
	(config: RequestOptionsType) => {
		if (config.loading) {
			openFullScreen()
		}
		const url = config.url
		if (url && (url?.indexOf('http://') > -1 || url?.indexOf('https://') > -1)) {
			return config
		}
		config.headers['authorization'] = storage.getItem('token')
		
		config.headers['x-app-sources'] = 'pc'
		return config;
	},
	(error: AxiosError) => {
		
		return Promise.reject(error);
	}
);

service.interceptors.response.use(
	(response: AxiosResponse<RequestResponse>):Promise<RequestResponse> => {
		closeFullScreen()
		if (response.status === 200) {
			const resp = response.data
			if (resp.code === 0) {
				return Promise.resolve(resp);
			} else if(resp.code === 409) {
				ElMessage.error('登陆已过期')
				localStorage.clear()
				router.push('/login')
				window.location.href = window.location.href
				return Promise.reject();
			} else {
				ElMessage.error(resp.message)
				return Promise.reject();
			}
		} else {
			ElMessage.error(response.data.message)
			return Promise.reject();
		}

	},
	(error: AxiosError) => {
		const resp = error.response
		closeFullScreen()
		if (resp?.status === 500) {
			ElMessage.error('网络错误，请稍后重试~')
			return Promise.reject(error)
		}
		if (error.message.includes('timeout')) {
			ElMessage.error('请求超时')
			return Promise.reject('timeout')
		}
		ElMessage.error(error.message)
		return Promise.reject(error);
	}
);

export default service;
